package biznussoft.metercor.fragments;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import biznussoft.metercor.MainActivity;
import biznussoft.metercor.R;
import biznussoft.metercor.StockTransferActivity;
import biznussoft.metercor.adapter.StockTransferLineDetailsAdapter;
import biznussoft.metercor.entity.StockTransferLineModel;
import biznussoft.metercor.entity.StockTransferModel;
import biznussoft.metercor.listener.Globallistener;
import biznussoft.metercor.lookup.StockTransferLookUp;
import biznussoft.metercor.utils.Session;

import com.example.zbarcodelibrary.ZBarConstants;
import com.example.zbarcodelibrary.ZBarScannerActivity;
import com.google.gson.Gson;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;

public class StockTransferDetailsFragment  extends Fragment implements OnTouchListener, OnClickListener{
	private GridView gv;
	private static final int ZBAR_SCANNER_REQUEST = 0;                                  
	private static final int ZBAR_QR_SCANNER_REQUEST = 1;
	public static RelativeLayout rrLot,rrSerial;
	private LinearLayout stocktransferview,newStocktransferlayout;
	private StockTransferModel model;
	private ArrayList<StockTransferLineModel> list;
	public static ArrayList<StockTransferLineModel> ItemIdList;
	private Globallistener listener;
	private RestClient client;
	public static TextView etLotId;
	private ImageView btSave,newStockTransferLine;
	public  static EditText etStockTransfer,etItemId;
	private static EditText etSerialId,etQuantityTransferred,etAdditionInformation;
	private String strSourceId,barcode,ItemId,qty,itemName;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.stocktransfer_details, null);
	}


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//setHasOptionsMenu(true);

	}

	@Override
	public void onAttach(Activity activity) {
		listener = (Globallistener) getActivity();
		super.onAttach(activity);
	}

	/*@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		MenuItem addAccount = menu.add("New");
		MenuItemCompat.setShowAsAction(addAccount, MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		addAccount.setIcon(R.drawable.add); 
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		if(item.getTitle().equals("New")){
			listener.getSignature("New");
			setHasOptionsMenu(false);
		}
		return super.onOptionsItemSelected(item);

	}*/

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		client = MainActivity.mActivity.client;
		newStocktransferlayout = (LinearLayout) getView().findViewById(R.id.newStocktransferlayout);
		rrLot = (RelativeLayout) getView().findViewById(R.id.rrlayout_lotId);
		rrSerial = (RelativeLayout) getView().findViewById(R.id.rrlayout_serialId);
		gv = (GridView) getView().findViewById(R.id.gridview);
		stocktransferview = (LinearLayout) getView().findViewById(R.id.stocktransferview);
		btSave= (ImageView) getView().findViewById(R.id.btTransferLinesave);
		btSave.setOnClickListener(this);
		newStockTransferLine = (ImageView) getView().findViewById(R.id.newStockTransferLine);
		newStockTransferLine.setOnClickListener(this);

		etSerialId = (EditText) getView().findViewById(R.id.etSerialId);
		etSerialId.setOnTouchListener(this);
		etSerialId.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {

				if(!hasFocus) {
					getItemId();                    
				}

			}
		});
		etLotId = (TextView) getView().findViewById(R.id.etLotId);
		etQuantityTransferred = (EditText) getView().findViewById(R.id.etQtyTransferred);
		etAdditionInformation = (EditText) getView().findViewById(R.id.etAdditional);

		etStockTransfer = (EditText) getView().findViewById(R.id.etStockTransfer);
		etStockTransfer.setText(Session.sStockTransfer);
		etItemId = (EditText) getView().findViewById(R.id.etitemId);
		etStockTransfer.setOnTouchListener(this);
		etItemId.setOnTouchListener(this);                      

	}

	public void displayEmployeeDetails(int position) {
		stocktransferview.setVisibility(View.VISIBLE);
		newStocktransferlayout.setVisibility(View.GONE);
		model = StockTransferFragment.list.get(position);
		strSourceId = model.getSourceLocation();
		list = StockTransferFragment.subContactsList.get(model.getId());
		try{
			gv.setAdapter(new StockTransferLineDetailsAdapter(getActivity(), list));
		}catch(Exception ex){
		}
	}

	public void insertNewStockTransfer(){
		setHasOptionsMenu(true);
		stocktransferview.setVisibility(View.GONE);
		newStocktransferlayout.setVisibility(View.GONE);
	}

	



	public void getBarCode(){
		Intent intent = new Intent(getActivity(), ZBarScannerActivity.class);
		startActivityForResult(intent, ZBAR_SCANNER_REQUEST);
	}

	@SuppressWarnings("static-access")
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case ZBAR_SCANNER_REQUEST:
		case ZBAR_QR_SCANNER_REQUEST:
			if (resultCode ==getActivity().RESULT_OK) {
				barcode = data.getStringExtra(ZBarConstants.SCAN_RESULT);
				etSerialId.setText(barcode);
			} else if(resultCode == getActivity().RESULT_CANCELED && data != null) {
				String error = data.getStringExtra(ZBarConstants.ERROR_INFO);
				if(!TextUtils.isEmpty(error)) {
				}
			}
			break;
		}
	}

	public String getItemId(){

		try{

			String accounts = "select id,FConnect__Item__c,FConnect__Serial_ID__c,FConnect__Quantity__c from FConnect__Inventory__c where FConnect__Site__c="+"'"+Session.sSource+"' and FConnect__Serial_ID__c="+"'"+etSerialId.getText().toString()+"'";

			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), accounts);

			client.sendAsync(restRequest, new AsyncRequestCallback() {  
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {      
						Log.i("NCS","RestResponse  is  :"+result.toString());
						JSONObject jsonObject1 = new JSONObject(result.asString());
						JSONArray jsonArray = jsonObject1.getJSONArray("records");



						if(jsonArray.length()!=0){
							ItemId = jsonArray.getJSONObject(0).getString("FConnect__Item__c");
							//itemName = jsonArray.getJSONObject(0).getString("Item_Name__c");
							qty = jsonArray.getJSONObject(0).getString("FConnect__Quantity__c");}else{
								AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
								builder.setTitle(R.string.fs360);
								builder.setMessage("No Records Available");
								builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog, int which) {
										dialog.dismiss();


									}
								});

								builder.show();
							}

						etItemId.setText(ItemId);
						etQuantityTransferred.setText(qty);


					} catch (Exception e) {
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});



		} catch (Exception e) {
			Log.i("NCS","Exception  2 is  :"+e.getMessage());
		}

		return "abc";
	}

	public void newStockTransferLine(){

		String objectType = "FConnect__Stock_Transfer_Line__c";                                 
		HashMap<String, Object> fields = new HashMap<String, Object>();
		fields.put("FConnect__Stock_Transfer__c",Session.sStockTransferId);                  
		fields.put("FConnect__Item__c",ItemId);
		fields.put("FConnect__Qty_Transferred__c",etQuantityTransferred.getText().toString());
		fields.put("FConnect__Serial_ID__c",etSerialId.getText().toString());           

		try {                
			RestRequest restRequest = RestRequest.getRequestForCreate(getString(R.string.api_version),objectType,fields);


			client.sendAsync(restRequest, new AsyncRequestCallback() {
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {   

						Log.i("TPT","Result is  is   :"+result);
						
							startActivity(new Intent(getActivity(),StockTransferActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
							Session.sSource="";


					}                                
					catch (Exception e) {
						Log.i("TPT","Exception 1 is   :"+e.getMessage());                      
					}
				}

				//@Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});
		} 
		catch (Exception e) {
			Log.i("TPT","Exception 2 is   :"+e.getMessage());

		}



	}


	@Override
	public boolean onTouch(View v, MotionEvent event) {

		switch (v.getId()) {
		

		case R.id.etStockTransfer:
			if(event.getAction() == MotionEvent.ACTION_UP){
				StockTransferLookUp lookUp = new StockTransferLookUp();
				lookUp.getItemLookUp(getActivity(), "source");                  
			}
			break;

		/*case R.id.etitemId:
			if(event.getAction() == MotionEvent.ACTION_UP){
				InventoryItemIdLookUp lookUp = new InventoryItemIdLookUp();
				lookUp.getItemLookUp(getActivity(), "source");    


			}
			break;*/
		case R.id.etSerialId:
			if(event.getAction() == MotionEvent.ACTION_UP){
				getBarCode();

			}
			break;

		default:
			break;
		}


		return false;
	}


	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		
		case R.id.newStockTransferLine:
			stocktransferview.setVisibility(View.GONE);
			newStocktransferlayout.setVisibility(View.VISIBLE);
			StockTransferDetailsFragment.rrSerial.setVisibility(View.VISIBLE);
			retriveItems();          

			break;

		case R.id.btTransferLinesave:
			newStockTransferLine();
			break;

		default:
			break;
		}


	}

	public void retriveItems(){

		try{  

			String accounts = "select id,FConnect__Item__c,FConnect__Serial_ID__c,FConnect__Lot_ID__c,FConnect__Quantity__c from FConnect__Inventory__c where FConnect__Site__c="+"'"+strSourceId+"'";

			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), accounts);

			client.sendAsync(restRequest, new AsyncRequestCallback() {
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {

						Log.i("NCS","Result is   :"+result.toString());

						JSONObject jsonObject1 = new JSONObject(result.asString());

						JSONArray jsonArray = jsonObject1.getJSONArray("records");

						ItemIdList = new ArrayList<StockTransferLineModel>();
						Gson _gson = new Gson();
						for(int i=0; i< jsonArray.length(); i++)
						{
							if(!jsonArray.isNull(i)){
								StockTransferLineModel bean = _gson.fromJson(jsonArray.getString(i), StockTransferLineModel.class);
								ItemIdList.add(bean);
							}
						}     


					} catch (Exception e) {
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);

				}
			});



		} catch (Exception e) {
			Log.i("NCS","Exception  2 is  :"+e.getMessage());
		}
	}





}